import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatbot/liaotian.dart';
import 'package:chatbot/yanses.dart';
import 'package:chatbot/shuju_guanli.dart';
import 'package:chatbot/shijian.dart';
import 'package:chatbot/shijian_bashi.dart';
import 'package:chatbot/juse_liebiao_shuju.dart';
import 'package:chatbot/juse_moxing.dart';
import 'package:chatbot/cunchu_guanli.dart';
import 'package:chatbot/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class JuseBiaoQianYemian extends StatefulWidget {
  final bool shifouXuanze;
  final SpeechToText? shuohua;

  final SpeechToTextProvider? shuohuaTigong;

  const JuseBiaoQianYemian(
      {super.key,
      this.shifouXuanze = false,
      required this.shuohua,
      required this.shuohuaTigong});

  @override
  _JuseBiaoQianYemianState createState() => _JuseBiaoQianYemianState();
}

class _JuseBiaoQianYemianState extends State<JuseBiaoQianYemian>
    with
        TickerProviderStateMixin,
        AutomaticKeepAliveClientMixin<JuseBiaoQianYemian> {
  late TabController biaoqianKongzhi;
  List biaoqianYe = [];
  List<JueseTou> biaoqianTOuList = [];

  @override
  void initState() {
    super.initState();
    bendihuoqu();
  }

  //是否需要更新当前界面
  wangluohuoqu(bool isUpdate) async {
    debugPrint("getRolesFromNet!!!!!!!!");
    int dangqianYemain = 1;
    List<JueSe> jueseList = [];
    bool zuihou = false;
    int totals = 0;
    while (!zuihou) {
      JueseLiebiao roleListModel =
          await QingQiuGuanLi.instance.huoquJuese(dangqianYemain);
      if (roleListModel.shuju.liebiao.isNotEmpty) {
        dangqianYemain += 1;
        totals = roleListModel.shuju.total;
        jueseList.addAll(roleListModel.shuju.liebiao);
        zuihou = roleListModel.shuju.isLastPage;
      }
    }
    if (isUpdate) {
      jiexiLiebiao(jueseList, true);
    }
    if (totals == jueseList.length) {
      debugPrint("save to local");
      String jsonString = json.encode(jueseList);
      CunChuGuanLi.cunJueseJson(jsonString);
    }
  }

  void jiexiLiebiao(List<dynamic> liebiao, bool wangluo) {
    if (liebiao.isNotEmpty) {
      debugPrint("local list size=${liebiao.length}");
      JueSe? zhiqianJuese;
      int index = -1;
      biaoqianTOuList = [];
      biaoqianYe = [];
      for (JueSe juese in liebiao) {
        if (zhiqianJuese == null || juese.fenlei != zhiqianJuese.fenlei) {
          index = index + 1;
          var jiedianJuese = JueseTou();
          jiedianJuese.shuju = [];
          jiedianJuese.biaoti = juese.fenlei;
          biaoqianYe.add(juese.fenlei);
          biaoqianTOuList.add(jiedianJuese);
          zhiqianJuese = juese;
        }

        biaoqianTOuList[index].shuju.add(juese);
      }
      biaoqianKongzhi = TabController(length: biaoqianYe.length, vsync: this);
    }
    setState(() {});
  }

  bendihuoqu() {
    String roleJsonString = CunChuGuanLi.huoquJueseJson();
    if (roleJsonString != "") {
      List mapList = json.decode(roleJsonString);
      List<JueSe> roleList = [];
      for (Map<String, dynamic> map in mapList) {
        roleList.add(JueSe.fromMap(map));
      }
      jiexiLiebiao(roleList, false);
      if (!widget.shifouXuanze) {
        wangluohuoqu(false);
      }
    } else {
      wangluohuoqu(true);
    }
  }

  isResponseSuccess(Map response) {
    return response.containsKey('code') && response['code'] == 200;
  }

  @override
  Widget build(BuildContext context) {
    return biaoqianYe.isEmpty
        ? Scaffold(
            backgroundColor: Yanse.qianse,
            body: Center(
              child: CupertinoActivityIndicator(
                  radius: 10.0, color: Yanse.jibenYanse),
            ),
          )
        : Scaffold(
            backgroundColor: Yanse.qianse,
            appBar: widget.shifouXuanze
                ? AppBar(
                    elevation: 0,
                    backgroundColor: Yanse.qianse,
                    leading: IconButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        icon: const Icon(
                          Icons.arrow_back_ios,
                          color: Colors.black,
                          size: 20,
                        )),
                    actions: [
                      InkWell(
                          onTap: () {
                            CunChuGuanLi.shezhiTishiJue("");
                            CunChuGuanLi.shezhiShouyeJuese("对话");
                            CunChuGuanLi.shezhiShouYeTishi(Utils.morenTishi);
                            ShijianGUanli.instance.shijianChe
                                .fire(QiehuanJuse());
                            Navigator.pop(context);
                          },
                          child: Padding(
                            padding: const EdgeInsets.only(right: 8.0),
                            child: Text(
                              "默认",
                              style: TextStyle(
                                  color: Yanse.jibenYanse,
                                  fontSize: 13,
                                  fontWeight: FontWeight.w700),
                            ),
                          ))
                    ],
                    title: Text(
                      "切换角色",
                      style: const TextStyle(
                          color: Colors.black,
                          fontSize: 16,
                          fontWeight: FontWeight.w600),
                    ),
                    bottom: PreferredSize(
                        preferredSize: Size.fromHeight(30.0),
                        child: TabBar(
                          isScrollable: true,
                          unselectedLabelColor: Color(0xff848691),
                          labelStyle: TextStyle(
                              color: Yanse.jibenYanse,
                              fontSize: 14,
                              fontWeight: FontWeight.w600),
                          unselectedLabelStyle: const TextStyle(
                              fontSize: 14, fontWeight: FontWeight.w600),
                          dividerColor: Yanse.shense,
                          indicatorColor: Yanse.jibenYanse,
                          controller: biaoqianKongzhi,
                          tabs: biaoqianYe
                              .map((e) => Tab(
                                    text: e,
                                    height: 30,
                                  ))
                              .toList(),
                        )),
                  )
                : PreferredSize(
                    preferredSize: Size.fromHeight(30.0),
                    child: SafeArea(
                        child: Center(
                      child: TabBar(
                        isScrollable: true,
                        unselectedLabelColor: Color(0xff848691),
                        labelStyle: TextStyle(
                            color: Yanse.jibenYanse,
                            fontSize: 15,
                            fontWeight: FontWeight.w600),
                        unselectedLabelStyle: const TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w600),
                        dividerColor: Yanse.shense,
                        indicatorColor: Yanse.jibenYanse,
                        controller: biaoqianKongzhi,
                        tabs: biaoqianYe
                            .map((e) => Tab(text: e, height: 30))
                            .toList(),
                      ),
                    ))),
            body: TabBarView(
              //构建
              controller: biaoqianKongzhi,
              children: biaoqianYe.map((e) {
                return JueseYemian(
                  jueseJiedianLiBiao: biaoqianTOuList,
                  biaoti: e,
                  xouanzeJuese: widget.shifouXuanze,
                  shuohua: widget.shuohua,
                  speechProvider: widget.shuohuaTigong,
                );
              }).toList(),
            ),
          );
  }

  @override
  void dispose() {
    // 释放资源
    biaoqianKongzhi.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}

class JueseYemian extends StatefulWidget {
  final List<JueseTou> jueseJiedianLiBiao;
  final String biaoti;
  final bool xouanzeJuese;
  final SpeechToText? shuohua;

  final SpeechToTextProvider? speechProvider;

  const JueseYemian(
      {super.key,
      required this.jueseJiedianLiBiao,
      required this.biaoti,
      required this.xouanzeJuese,
      required this.shuohua,
      required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return JueseState(jueseJieDianList: jueseJiedianLiBiao, biaoti: biaoti);
  }
}

class JueseXiang extends StatelessWidget {
  final JueSe juese;
  final SpeechToText? shuohua;
  final bool xuanzeJuese;
  final SpeechToTextProvider? speechProvider;

  const JueseXiang(
      this.juese, this.xuanzeJuese, this.shuohua, this.speechProvider);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      highlightColor: Colors.transparent, // 透明色
      splashColor: Colors.transparent, // 透明色
      onTap: () {
        if (xuanzeJuese) {
          CunChuGuanLi.shezhiTishiJue(juese.tishici);
          CunChuGuanLi.shezhiShouyeJuese(juese.biaoti);
          CunChuGuanLi.shezhiShouYeTishi("${juese.biaoti}:${juese.fubiaoti}");
          ShijianGUanli.instance.shijianChe.fire(QiehuanJuse());
          Navigator.pop(context);
        } else {
          Navigator.push(context,
              CupertinoPageRoute(builder: (BuildContext context) {
            return LiaotianYemian(
              tishiCi: juese.tishici,
              jueseMing: juese.biaoti,
              jueseTishi: juese.fubiaoti,
              leixing: juese.type,
              tishiTou: juese.tishibiaoti,
              shuoHua: shuohua!,
              kouyuTiGong: speechProvider!,
            );
          }));
        }
      },
      child: Container(
          margin: const EdgeInsets.fromLTRB(12, 12, 0, 0),
          height: (MediaQuery.of(context).size.width - 36) * 1.1 / 2,
          width: (MediaQuery.of(context).size.width - 36) / 2,
          child: Stack(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: CachedNetworkImage(
                    imageUrl: juese.tupian,
                    width: (MediaQuery.of(context).size.width - 36) / 2,
                    height: (MediaQuery.of(context).size.width - 36) * 1.1 / 2,
                    fit: BoxFit.cover,
                    // placeholder: (context, url) =>
                    //     const CircularProgressIndicator(color: Colors.grey),
                    errorWidget: (context, url, error) {
                      // debugPrint(error);
                      return const Icon(Icons.error);
                    },
                  )),
              ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: BackdropFilter(
                      // 背景过滤器
                      filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
                      child: Opacity(
                          opacity: 0.7,
                          child: Container(
                            alignment: Alignment.center,
                            height: double.infinity,
                            width: double.infinity,
                            decoration:
                                BoxDecoration(color: Colors.grey.shade900),
                          )))),
              Padding(
                padding: EdgeInsets.fromLTRB(12, 18, 12, 18),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      juese.biaoti,
                      style: const TextStyle(
                          color: Colors.white,
                          fontSize: 22,
                          fontWeight: FontWeight.w600),
                    ),
                    Expanded(child: Container()),
                    Text(
                      juese.fubiaoti,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
              ),
            ],
          )),
    );
  }
}

class JueseState extends State<JueseYemian> {
  final List<JueseTou> jueseJieDianList;
  List<JueSe> jueseLiebiao = [];
  final String biaoti;

  JueseState({required this.jueseJieDianList, required this.biaoti});

  @override
  void initState() {
    super.initState();
    setState(() {
      for (JueseTou section in jueseJieDianList) {
        if (section.biaoti == biaoti) {
          jueseLiebiao.addAll(section.shuju);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Yanse.qianse,
      body: ListView.builder(
          itemCount: jueseLiebiao.length ~/ 2 + jueseLiebiao.length % 2,
          itemBuilder: (BuildContext context, int index) {
            return Row(
              children: [
                JueseXiang(jueseLiebiao[index * 2], widget.xouanzeJuese,
                    widget.shuohua, widget.speechProvider),
                jueseLiebiao.length > (index * 2 + 1)
                    ? JueseXiang(
                        jueseLiebiao[index * 2 + 1],
                        widget.xouanzeJuese,
                        widget.shuohua,
                        widget.speechProvider)
                    : Container()
              ],
            );
          }),
    );
  }
}
